<?php
class Shop_Model_Observer_AttacheImageToProduct extends Promotor_Observable_Observer_Abstract {

	public function update(Promotor_Observable_List $list, $productId = null, Zend_Form $form = null) {
		if (is_array($productId)) {
			$productId = isset($productId['id'])
				? $productId['id']
				: current($productId);
		}
		if (null === $productId) {
			$this->_setStatus(self::NULL);
			return;
		}
		
		if (null === $form) {
			$this->_setStatus(self::NULL);
			return;
		}

		/* @var $form Shop_Form_Product_Add */
		$subForm = $form->getSubForm('imagetab');

		/* @var $file Zend_Form_Element_File */
		$file = $subForm->getElement('image_main');
		if ($file->isReceived()) {
			$imageId = $this->_save($file , $productId);

			if (is_array($imageId)) {
				$imageId = isset($imageId['id'])
					? $imageId['id']
					: current($imageId);
			}

			$product = new Shop_Model_Product();
			$product->setMainImage($productId, $imageId);

			$this->_addMessage($product->getStatus());
			$this->_addMessage($product->getMessages());
		}
		if (isset($_POST['editable']) 
				&& isset($_POST['editable']['main_image'])
					&& is_numeric($_POST['editable']['main_image']))
		{
			$product = new Shop_Model_Product();
			$product->setMainImage($productId, $_POST['editable']['main_image']);
		}
		
		
		$file = $subForm->getElement('image1');
		$this->_save($file, $productId);

		$file = $subForm->getElement('image2');
		$this->_save($file, $productId);
		
		$this->_setStatus(self::SUCCESS);
	}

	/**
	 * @var Shop_Model_Image
	 */
	protected $_image;
	
	/**
	 * @return Shop_Model_Image
	 */
	public function getImage() {
		if (null === $this->_image) {
			$this->_image = new Shop_Model_Image();
		}
		return $this->_image;
	}
	
	/**
	 * @param Zend_Form_Element_File $file
	 * @param integer $productId
	 * @return mixed
	 */
	protected function _save(Zend_Form_Element_File $file, $productId) {
		if ($file->isReceived()) {
			$image = $this->getImage();
			
			$data = array(
				'image' => $file->getFileName(null, false),
				'product_id' => $productId
			);
			
			$imageId = $image->save($data);

			$this->_addMessage($image->getStatus());
			$this->_addMessage($image->getMessages());

			return $imageId;
		}
	}
}